package com.zzyl.nursing.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.dto.UserLoginRequestDto;
import com.zzyl.nursing.domain.pojo.FamilyMember;
import com.zzyl.nursing.domain.vo.LoginVo;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 老人家属Service业务层处理
 *
 * @author alexis
 * @date 2025-05-26
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private TokenService tokenService;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return familyMemberMapper.deleteById(id);
    }


    /**
     * 小程序登录
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 一、认证：根据openId-->family_member表查询是否存在该用户
        String code = userLoginRequestDto.getCode();
        String phoneCode = userLoginRequestDto.getPhoneCode();
        String openId = wechatService.getOpenId(code);
        FamilyMember member = this.getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));
        // 二、表维护：获取用户phone和昵称数据-->新增用户或者修改用户
        String accessToken = wechatService.getAccessToken();
        String phoneNumber = wechatService.getPhoneNumber(accessToken, phoneCode, openId);
        if (ObjectUtil.isNull(member)) {
            // 新用户：新增
            member = FamilyMember.builder() //赋值属性
                    .phone(phoneNumber)
                    .name(generateUsername(phoneNumber))
                    .openId(openId)
                    .build();
            this.save(member);
        } else {
            // 老用户：修改手机号(表中手机号和现在登录手机号不一致才会修改)
            if (!StrUtil.equals(member.getPhone(), phoneNumber)) {
                member.setPhone(phoneNumber);
                this.updateById(member);
            }
        }
        // 三、产生token构建LoginVo对象
        Map<String, Object> claims = MapUtil.<String, Object>builder()
                .put("userId", member.getId()).build();
        String token = tokenService.createToken(claims); //调用获取token的方法,传入含用户id的对象
        return LoginVo.builder()
                .token(token)
                .nickName(generateUsername(phoneNumber)).build();
    }

    @Override
    public void getMy() {
        log.info("FamilyMemberService中线程==>{}", Thread.currentThread().getId());
        Long userId = UserThreadLocal.getValue();
        log.info("从ThreadLocal中获取的用户id为:{}", userId);
    }


    private static final List<String> IDIOMS = Arrays.asList(
            "画蛇添足", "掩耳盗铃", "刻舟求剑", "亡羊补牢", "守株待兔",
            "叶公好龙", "自相矛盾", "滥竽充数", "杯弓蛇影", "买椟还珠"
            // 可以继续添加更多成语
    );

    private static final Random RANDOM = new Random();

    /**
     * 生成用户名
     *
     * @param phoneNumber 手机号
     * @return 生成的用户名
     */
    private String generateUsername(String phoneNumber) {
        // 随机选取一个四字成语
        String randomIdiom = IDIOMS.get(RANDOM.nextInt(IDIOMS.size()));
        // 获取手机号后四位
        String lastFourDigits = phoneNumber.substring(Math.max(0, phoneNumber.length() - 4));
        // 组合成用户名
        return randomIdiom + lastFourDigits;
    }
}
